#include "AsioIOServicePool.h"
#include<iostream>
using namespace std;

AsioIOServicePool::~AsioIOServicePool()
{
	Stop();
	std::cout << "AsioIOServicePool destruct" << std::endl;
}

boost::asio::io_context& AsioIOServicePool::GetIOservice()
{
	auto& service = _ioService[_nextIOService++];
	if (_nextIOService == _ioService.size())
	{
		_nextIOService = 0;
	}

	return service;
}

void AsioIOServicePool::Stop()
{
	for (auto& work : _work) {
		work->get_io_context().stop();
		work.reset();
	}

	for (auto& t : _thread) {
		t.join();
	}


}

AsioIOServicePool::AsioIOServicePool(std::size_t size):_ioService(size),_work(size),_nextIOService(0)
{
	for (std::size_t i = 0; i < _work.size(); ++i) {
		_work[i] = std::unique_ptr<WORK>(new WORK(_ioService[i]));
	}

	for (std::size_t i = 0; i < _ioService.size(); ++i)
	{
		_thread.emplace_back([this, i]() {
			_ioService[i].run();
			});
	}
}
